/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentaPPal.java
 *
 * Created on 31-ago-2011, 1:04:00
 */
package Ventanas;

import Controladores.CtrlInicioSesion;
import Controladores.CtrlModifUmbral;
import Controladores.CtrlUsuarios;
import DataTypes.DataConexion;
import Interfaces.Factory;
import Interfaces.ICtrlConexiones;
import Interfaces.ICtrlInicioSesion;
import Interfaces.ICtrlModifUmbral;
import Persistencia.ICtrlPersistir;
import Interfaces.ICtrlUsuarios;
import Persistencia.CtrlPersistencia;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import objetos.Reloj;

/**
 *
 * @author Sebas
 */
public class VentanaPPalServCentral extends javax.swing.JFrame {

    Reloj rej = new Reloj();

    public VentanaPPalServCentral(String title) throws HeadlessException {
        super(title);
        initComponents();
        ICtrlModifUmbral ctrl = CtrlModifUmbral.getInstance();
        int punt = ctrl.getUmbral();
        jLabel2.setText("Puntaje minimo: " + punt);
        modificarFecha.setVisible(false);
        jCalendarButton1.setTargetDate(Calendar.getInstance().getTime());
        jTimeButton1.setTargetDate(Calendar.getInstance().getTime());
        FechaActual.setText("HOLA");
        Timer timer = new Timer();
        timer.schedule(new DoTick(), 0, 1000);

    }

    private void actualizarTablaConexiones() {
        ICtrlConexiones ctrlConex = Factory.getInstance().getConexiones();
        ArrayList<DataConexion> conexiones = ctrlConex.getConexiones();
        DefaultTableModel model = (DefaultTableModel) jTable_conexiones.getModel();

        model.setRowCount(0);
        if (!conexiones.isEmpty()) {
            Object[] fila = new Object[3];
            Iterator<DataConexion> itera = conexiones.iterator();
            DataConexion con;
            while (itera.hasNext()) {
                con = itera.next();
                fila[0] = con.getTipoAplic().toString();
                fila[1] = con.getIp();
                fila[2] = con.getUsrLogueado();
                model.addRow(fila);
            }
        }
    }

    class DoTick extends TimerTask {

        Calendar cal = Calendar.getInstance();
        DateFormat formateador = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

        @Override
        public void run() {
            cal = (rej.getTime().getCalendar());
            FechaActual.setText(formateador.format(cal.getTime()));

            //Actualizar Conexiones.
            actualizarTablaConexiones();
        }
    }

    public VentanaPPalServCentral() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jSpinner1 = new javax.swing.JSpinner();
        jLabel1 = new javax.swing.JLabel();
        Persistir = new javax.swing.JButton();
        Cargar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        modificarFecha = new javax.swing.JPanel();
        jCalendarButton1 = new net.sourceforge.jcalendarbutton.JCalendarButton();
        jTimeButton1 = new org.sourceforge.jcalendarbutton.JTimeButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        FechaActual = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable_conexiones = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("RED(Servidor Central)- Ventana principal");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel1.setText("SERVIDOR CENTRAL");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 20, -1, -1));

        Persistir.setText("Persistir");
        Persistir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                PersistirMouseClicked(evt);
            }
        });
        getContentPane().add(Persistir, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 80, 100, 50));

        Cargar.setText("Cargar datos");
        Cargar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CargarMouseClicked(evt);
            }
        });
        getContentPane().add(Cargar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 80, -1, 50));

        jButton1.setText("Modificar umbral minino para mostrar comentarios");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 80, -1, 50));

        jLabel2.setText("jLabel2");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(27, 22, -1, -1));

        modificarFecha.setEnabled(false);

        jCalendarButton1.setText("Seleccionar fecha");

        jTimeButton1.setText("Seleccionar hora");

        jLabel3.setText("Hora :");

        jLabel4.setText("Fecha :");

        jLabel5.setText("MODIFICAR HORA");

        jButton2.setText("Modificar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout modificarFechaLayout = new javax.swing.GroupLayout(modificarFecha);
        modificarFecha.setLayout(modificarFechaLayout);
        modificarFechaLayout.setHorizontalGroup(
            modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(modificarFechaLayout.createSequentialGroup()
                .addGroup(modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, modificarFechaLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTimeButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, modificarFechaLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addGroup(modificarFechaLayout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jCalendarButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
                .addGap(2, 2, 2))
        );
        modificarFechaLayout.setVerticalGroup(
            modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(modificarFechaLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
                    .addGroup(modificarFechaLayout.createSequentialGroup()
                        .addGroup(modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jCalendarButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(modificarFechaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jTimeButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        getContentPane().add(modificarFecha, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 130, 340, 100));

        FechaActual.setText("jLabel6");
        getContentPane().add(FechaActual, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 10, 140, -1));

        jLabel7.setFont(new java.awt.Font("Tahoma 18 Negrita", 0, 12));
        jLabel7.setForeground(new java.awt.Color(0, 102, 0));
        jLabel7.setText("Conexiones al Servidor:");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 210, -1, -1));

        jTable_conexiones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Aplicacion", "IP", "Usuario"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable_conexiones);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 240, 630, 160));

        jMenu1.setText("File");

        jMenuItem2.setText("Cerrar Sesion");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Exit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Reloj del sistema");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        jMenuItem3.setText("Consultar fecha");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem3);

        jMenuItem4.setText("Modificar fecha");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem4);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    // TODO add your handling code here:
    int confirma = JOptionPane.showConfirmDialog(null, "Confirma que desea salir de la aplicacion?", "Cerrar aplicación", JOptionPane.YES_NO_OPTION);
    if (confirma == 0) {
        System.exit(0);
    }

}//GEN-LAST:event_jMenuItem1ActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
    // TODO add your handling code here:
    ICtrlInicioSesion ctrlInicio = new CtrlInicioSesion();
    int confirma = JOptionPane.showConfirmDialog(null, "Confirma que desea cerrar sesión de administrador?", "Cerrar sesión", JOptionPane.YES_NO_OPTION);
    if (confirma == 0) {
        ctrlInicio.logout();
        LoginServCent log = new LoginServCent();
        setVisible(false);
        log.setVisible(true);
        log.setLocationRelativeTo(null);
    }
}//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        // TODO add your handling code here:


        Calendar tiempo = rej.getTime().getCalendar();
        String strTiempo = "hh:mm:ss\n"
                + tiempo.get(Calendar.HOUR) + ":"
                + tiempo.get(Calendar.MINUTE) + ":"
                + tiempo.get(Calendar.SECOND);
        JOptionPane.showMessageDialog(null, strTiempo + "   Fecha del sistema");
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void PersistirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_PersistirMouseClicked

        ICtrlPersistir per = new CtrlPersistencia();
        ICtrlUsuarios usu = new CtrlUsuarios();
        JFileChooser fc = new JFileChooser();
        File file = null;
        String PathCarpeta = null;

        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                file = fc.getSelectedFile();
                //para devolver el path de la carpeta seleccionada
                PathCarpeta = file.getPath();

                per.guardarUsuarios(usu.listarDUsuarios(), PathCarpeta);
                per.guardaAmistad(usu.listarDUsuarios(), PathCarpeta);
                per.guardarEventos(usu.listarDUsuarios(), PathCarpeta);
                per.guardarUsuarioEvento(PathCarpeta);
                per.guardarEntradasMuro(PathCarpeta);
                per.guardarContenidos(PathCarpeta);
                per.guardarGrupos(PathCarpeta);
                per.guardarUmbralMinimo(PathCarpeta);

                per.guardarHistorial(PathCarpeta);


                JOptionPane.showMessageDialog(null, "Se guardaron los datos correctamente.");
            } catch (IOException ex) {
                Logger.getLogger(VentanaPPalServCentral.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_PersistirMouseClicked

    private void CargarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CargarMouseClicked
        // TODO add your handling code here:
        ICtrlPersistir per = new CtrlPersistencia();
        ICtrlUsuarios usu = new CtrlUsuarios();
        JFileChooser fc = new JFileChooser();
        File file = null;
        fc.setDialogType(2);
        String PathCarpeta = null;
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            //para devolver el path de la carpeta seleccionada
            PathCarpeta = file.getPath();

            per.CargarUsuarios(PathCarpeta);
            per.CargarAmistades(PathCarpeta);
            per.cargarGrupos(PathCarpeta);
            per.CargarEntradasAMuro(PathCarpeta);
            per.cargarEventos(PathCarpeta);
            per.cargarUmbralMinimo(PathCarpeta);
            per.cargarEtiquetas(PathCarpeta);
            per.cargarHistoriales(PathCarpeta);
            JOptionPane.showMessageDialog(rootPane, "Se cargaron los datos correctamente.");
            ICtrlModifUmbral ctrlUmb = Factory.getInstance().getModificarUmbral();
            int umb = ctrlUmb.getUmbral();
            jLabel2.setText("Puntaje minimo: " + umb);
        }
    }//GEN-LAST:event_CargarMouseClicked

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1MouseClicked

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        // TODO add your handling code here:
        modificarFecha.setVisible(true);



    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        Calendar cal = Calendar.getInstance();
        cal.setTime(jCalendarButton1.getTargetDate());
        cal.set(Calendar.HOUR_OF_DAY, jTimeButton1.getTargetDate().getHours());
        cal.set(Calendar.MINUTE, jTimeButton1.getTargetDate().getMinutes());
        rej.setReloj(cal);
        JOptionPane.showMessageDialog(null, "Se modifico la fecha correctamente.");
        modificarFecha.setVisible(false);


    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        ICtrlModifUmbral ctrlModif = CtrlModifUmbral.getInstance();
        String strPunt = JOptionPane.showInputDialog("Puntaje minimo para mostrar:");
        int punt = Integer.parseInt(strPunt);
        ctrlModif.modificarUmbral(punt);
        jLabel2.setText("Puntaje minimo: " + punt);
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new VentanaPPalServCentral().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cargar;
    private javax.swing.JLabel FechaActual;
    private javax.swing.JButton Persistir;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private net.sourceforge.jcalendarbutton.JCalendarButton jCalendarButton1;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JTable jTable_conexiones;
    private org.sourceforge.jcalendarbutton.JTimeButton jTimeButton1;
    private javax.swing.JPanel modificarFecha;
    // End of variables declaration//GEN-END:variables
}
